﻿/* License
 * 
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, Sylvain PONTOREAU (pontoreau.sylvain@outlook.com / sylvain.pontoreau.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Xlsx.ComponentModel;
using Xlsx.ComponentModel.Enums;
using Xlsx.DataBinder.Collections;
using Xlsx.DataBinder.Resources;

namespace Xlsx.DataBinder
{
    /// <summary>
    /// Xlsx Skin Manager.
    /// </summary>
    public static class XlsxSkinManager
    {
        /// <summary>
        /// Private dictionary of skins
        /// </summary>
        private static Dictionary<XlsxSkinType, XlsxSkin> Skins { get; set; } 

        /// <summary>
        /// Xlsx skin for header
        /// </summary>
        public static XlsxSkin XlsxHeader 
        {
            get
            {
                XlsxSkin skin;
                return (Skins.ContainsKey(XlsxSkinType.Header) && Skins.TryGetValue(XlsxSkinType.Header, out skin))
                    ? skin 
                    : XlsxSkin.Default;                    
            }
        }

        /// <summary>
        /// Xlsx skin for row
        /// </summary>
        public static XlsxSkin XlsxRow 
        {
            get
            {
                XlsxSkin skin;
                return (Skins.ContainsKey(XlsxSkinType.Row) && Skins.TryGetValue(XlsxSkinType.Row, out skin))
                    ? skin
                    : XlsxSkin.Default;
            }
        }

        /// <summary>
        /// Xlsx skin for alternate row
        /// </summary>
        public static XlsxSkin XlsxAlternateRow 
        {
            get
            {
                XlsxSkin skin;
                return (Skins.ContainsKey(XlsxSkinType.AlternateRow) && Skins.TryGetValue(XlsxSkinType.AlternateRow, out skin))
                    ? skin
                    : XlsxSkin.Default;
            }
        }

        /// <summary>
        /// Static Ctor
        /// </summary>
        static XlsxSkinManager()
        {
            Skins = new Dictionary<XlsxSkinType, XlsxSkin>();
        }

        /// <summary>
        /// Load skins
        /// </summary>
        /// <param name="hearderSkin">Header skin</param>
        /// <param name="rowSkin">Row skin</param>
        /// <param name="alternateRowSkin">AlternateRow skin</param>
        public static void Load(XlsxSkin hearderSkin, XlsxSkin rowSkin, XlsxSkin alternateRowSkin)
        {
            if (Skins.Count > 0)
                Skins.Clear();

            Skins.Add(XlsxSkinType.Header, hearderSkin);
            Skins.Add(XlsxSkinType.Row, rowSkin);
            Skins.Add(XlsxSkinType.AlternateRow, alternateRowSkin);
        }

        /// <summary>
        /// Load skins from a xml file
        /// </summary>
        /// <param name="skinFilePath">Xml skin file path</param>
        public static void Load(string skinFilePath)
        {
            //check file path
            if (skinFilePath.Length >= 5 && skinFilePath.EndsWith(XlsxFormat.FileFormat))
            {
                TextReader reader = null;

                try
                {
                    var serializer = new XmlSerializer(typeof(List<XlsxSkinDataItem>));
                    reader = new StreamReader(skinFilePath);
                    var skinList = (List<XlsxSkinDataItem>)serializer.Deserialize(reader);

                    Load(skinList.Single(x => x.Type == XlsxSkinType.Header).Value,
                         skinList.Single(x => x.Type == XlsxSkinType.Row).Value,
                         skinList.Single(x => x.Type == XlsxSkinType.AlternateRow).Value);
                }
                catch (Exception ex)
                {
                    throw new XlsxDataBinderException(string.Format(XlsxException.FileLoadFailed, skinFilePath), ex);
                }
                finally
                {
                    if (reader != null)
                        reader.Close();
                }
            }
            else
            {
                throw new XlsxDataBinderException(string.Format(XlsxException.WrongFileFormat, skinFilePath));
            }
        }

        /// <summary>
        /// Save Skins
        /// </summary>
        /// <param name="skinDirectoryPath">Directory to save the skins</param>
        /// <param name="fileName">File name</param>
        public static void Save(string skinDirectoryPath, string fileName)
        {
            var filePath = string.Empty;

            TextWriter writer = null;

            try
            {
                var lists = Skins.Select(kp => new XlsxSkinDataItem
                    {
                        Type = kp.Key, Value = kp.Value
                    }).ToList();

                filePath = new StringBuilder(skinDirectoryPath).Append(fileName).Append(XlsxFormat.FileFormat).ToString();
                var serializer = new XmlSerializer(typeof(List<XlsxSkinDataItem>));
                writer = new StreamWriter(filePath);
                serializer.Serialize(writer, lists);
            }
            catch (Exception ex)
            {
                throw new XlsxDataBinderException(string.Format(XlsxException.FileSaveFailed, filePath), ex);
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }
    }
}
